<?php
namespace app\api\controller;

use app\BaseController;
use think\captcha\facade\Captcha;
use app\api\model\AdminUser as User;
use think\facade\Request;
use app\api\validate\UserValidate;
use thans\jwt\facade\JWTAuth;
use think\facade\Cache;
class Login extends BaseController
{


    public function check_login(){

        $data = Request::post();

        //验证表单
        $validate = new UserValidate;
        $result = $validate->check($data);

        if(!$result){
           return renderError($validate->getError());
        }

        //验证码
//        $check_code = $this->verify($data['code']);
//
//        if(!$check_code)return renderError('验证码不正确');

        //  账号密码是否正确
        $user = User::userdetail($data['username']);
        if(!$user){
            return renderError('账号不存在');
        }
        $res = $this->check_user($user,$data);
        if(!$res){
            return renderError('账号或者密码不正确');
        }
        $user_data = [
            'user_id' =>$user['id'],
            'username' => $user['username'],
            'name' => $user['name'],
            'avatar'=>$user['avatar'],
            'is_login'=>1,

        ];
//        session('User',$user_data);
        //生成token
        $token = JWTAuth::builder($user_data);

        Cache::tag('Cache')->set('token',$token,86400 * 7);
        $user_data['token'] = $token;

        return renderSuccess('登录成功',$user_data);

    }
    /*
     * 检查密码
     */
    public function check_user($user,$data){
        if($user['password'] != MD5(MD5($data['password'])))return false;
        return true;
    }
    /*
     * 验证码校验
     */
    public function verify($code)
    {

        $res = Captcha::check($code);

//        $res = Captcha::check_redis($code);
        if(!$res){
            return false;
        }
        return true;
    }

    /*
     * 注销登录
     */
    public function logout(\think\Request $request){

        $tokenStr = JWTAuth::token()->get();
        JWTAuth::invalidate($tokenStr);
        Cache::clear();
        return renderSuccess('注销成功');
    }

}
